package cn.edu.scau.liangshanhero.client;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.Map.Entry;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import cn.edu.scau.liangshanhero.configurateUtf8Filter.WebXMLConfigureUTF8FilterByDOM;
import cn.edu.scau.liangshanhero.localization.ChinezationUtil;
import cn.edu.scau.liangshanhero.pageEncodingIso2Utf8.ReplaceStringOfExtendedFileInDirectionary;
import cn.edu.scau.liangshanhero.util.Messages;

import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Label;

public class SwtMainWindow {

	
	protected Shell shell;//主工具界面
	private Text informationSelectProject;//
	private Label projectRootPathLabel;
	protected static String projectRootPath;//指定的项目的根路径
//	private static String selectProjectLocalizationPath;//选中的项目本地化资源文件夹
	protected static String selectProject;//下拉列表款选中的项目名称
	protected static File selectWebXMLPath;//web.xml文件
	
	static Set<?> english2ChineseSet = new HashSet();// 单词2中文的映射中的英语单词的集合
	protected static Map<String, String> propertiesValueWordMap;
	protected static List<File> sourcePropertiesFileList;
	protected static Vector<File> sourcePropertiesFileVector;
	protected static Text[] englishText;
	protected static Text[] chineseText;
	protected static String selectProjectPath;//选中的项目路径

	public static void main(String[] args) {
		try {
			SwtMainWindow window = new SwtMainWindow();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(900, 722);
		shell.setText("Java项目整理小工具");

		TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
		tabFolder.setBounds(0, 0, 835, 615);

		TabItem mainTabItem = new TabItem(tabFolder, SWT.NONE);
		mainTabItem.setText("主面板");

		Composite compositeMainTabItem = new Composite(tabFolder, SWT.NONE);
		mainTabItem.setControl(compositeMainTabItem);
//		该方法获取所有的项目，并将项目赋值给combo
//		选中的项目的.project的文件路径
		informationSelectProject = new Text(compositeMainTabItem, SWT.BORDER);
		informationSelectProject.setText(Messages.SwtMainWindow_informationSelectProject_text);
		informationSelectProject.setBounds(10, 26, 154, 23);

		
		
//		中文过滤器配置
		Button chineseFilterWebXMLConfigureButton = new Button(compositeMainTabItem, SWT.NONE);
		chineseFilterWebXMLConfigureButton.addSelectionListener(new UTF8FilterWebXmlConfigurationListener());
		chineseFilterWebXMLConfigureButton.setBounds(10, 211, 129, 27);
		chineseFilterWebXMLConfigureButton.setText("中文过滤器配置");
		
//		本地化部分的界面设计
		TabItem chinezation = new TabItem(tabFolder, SWT.NONE);
		chinezation.setText("中文化");
		
		final Composite compositeLocalizationTabItem = new Composite(tabFolder, SWT.NONE);
		chinezation.setControl(compositeLocalizationTabItem);
		
		
		
		final Table table = new Table(compositeLocalizationTabItem, SWT.MULTI | SWT.BORDER);
		table.setLocation(10, 29);
		table.setSize(737, 513);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		TableColumn tableColumnEnglish = new TableColumn(table, SWT.CENTER);
		tableColumnEnglish.setWidth(200);
		tableColumnEnglish.setText(Messages.FileUtil_0);
		TableColumn tableColumnChinese = new TableColumn(table, SWT.CENTER);
		tableColumnChinese.setWidth(200);
		tableColumnChinese.setText(Messages.FileUtil_23);
		
		Button localizationButton = new Button(compositeMainTabItem, SWT.NONE);
	
//		本地化按钮点击后，本地化tab将显示，并且列表会显示，且按钮可以被使用
		localizationButton.addSelectionListener(new LocalizationInitializatorListener(table));
		localizationButton.setBounds(10, 147, 414, 42);
		localizationButton.setText(Messages.SwtMainWindow_localizationButton_text);
		/**
		 * 页面字符编码替换
		 * 
		 * */
		Button btnutf = new Button(compositeMainTabItem, SWT.NONE);
		btnutf.addSelectionListener(new PageEncodingListener());
		btnutf.setBounds(10, 260, 221, 27);
		btnutf.setText(Messages.ToolSwtMainWindow_btnutf_text);
		
		Button button = new Button(compositeMainTabItem, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
//				打开文件夹，选中项目的根目录
				DirectoryDialog directoryDialog = new DirectoryDialog(shell);
				directoryDialog.setMessage("setMessage");
				directoryDialog.setText("setText");
				projectRootPath = directoryDialog.open();
				projectRootPathLabel.setText(projectRootPath);
//				directoryDialog.setFilterPath("C://");
				
				System.out.println("选中的项目的根路径是："+projectRootPath);
			}
		});
		button.setBounds(265, 19, 159, 30);
		button.setText(Messages.SwtMainWindow_button_text);
		
		projectRootPathLabel = new Label(compositeMainTabItem, SWT.NONE);
		projectRootPathLabel.setBounds(20, 73, 404, 20);
		projectRootPathLabel.setText(Messages.SwtMainWindow_label_text);
		
		Label lblmap = new Label(compositeMainTabItem, SWT.NONE);
		lblmap.setBounds(10, 99, 414, 42);
		lblmap.setText(Messages.SwtMainWindow_lblmap_text);
		
		
//		表格下的确定按钮
		Button btn = new Button(compositeLocalizationTabItem, SWT.NONE);
		btn.setBounds(248, 550, 62, 22);
		btn.setText(Messages.SwtMainWindow_btn_text);
		btn.setVisible(true);
		btn.addMouseListener(new ChinezationListener());

	}
	
/***
 * 本地化监听器
 * @author Liang Zaoqing
 *
 */

	private static class LocalizationInitializatorListener extends SelectionAdapter {
		private final Table table;

		private LocalizationInitializatorListener(Table table) {
			this.table = table;
		}

//		点击本地化后的操作。
		@Override
		public void widgetSelected(SelectionEvent e) {
			// (1)获取目录中所有的.properties文件
			String sourcePropertiesFilesDirectory=projectRootPath+"/resources/bundles/";
			sourcePropertiesFileList = ChinezationUtil.getSourcePropertiesFileList(new File(sourcePropertiesFilesDirectory));
			//				所有的源文件列表
			sourcePropertiesFileVector=new Vector<File>(50,10);
			// (2)所有的属性文件获取后，依次读取出所有的行，并将后面的单词放到一个集合中。
			propertiesValueWordMap = ChinezationUtil.putAllPropertiesFileEnglishWord2Map(sourcePropertiesFileVector, sourcePropertiesFileList,sourcePropertiesFilesDirectory);
			// (3)保存所有的映射配置，并生成输出文件
			//准备不要的
			//				ChinezationUtil.createTargetPropertiesFiles(sourceFileVector, propertiesValueWordMapSet, selectProjectLocalizationPath, compositeLocalizationTabItem);
			//	(4)
			english2ChineseSet = propertiesValueWordMap.entrySet();// 单词2中文的映射中的英语单词的集合
			//(5) 选择了本地化后，初始化列表中的表格的内容。
			initialTable();
			System.out.print("本地化初始化完成！！！");
		}

		//选择了本地化后，初始化列表中的表格的内容。
		private void initialTable() {
			englishText = new Text[english2ChineseSet.size()];
			chineseText = new Text[english2ChineseSet.size()];
			int wordIndex = 0;// 单词数组的下标
			
			Iterator<?> word2ChineseSet4TableIterator = english2ChineseSet.iterator();

			while (word2ChineseSet4TableIterator.hasNext()) {
				Entry<?, ?> word2ChineseEntry = (Entry<?, ?>) word2ChineseSet4TableIterator.next();
				word2ChineseEntry.getKey();// 英语单词
				word2ChineseEntry.getValue();// 英语单词的中文

				TableItem tableItem = new TableItem(table, SWT.NONE);

				//				表格中的每一行内容
				englishText[wordIndex] = new Text(table, SWT.NONE);
				englishText[wordIndex].setText(word2ChineseEntry.getKey().toString());

				tableItem.setText(0, englishText[wordIndex].getText().toString());

				chineseText[wordIndex] = new Text(table, SWT.NONE);
				chineseText[wordIndex].setText((word2ChineseEntry.getValue() == null) ? "" : word2ChineseEntry.getValue().toString());
				TableEditor tableEditor = new TableEditor(table);
				tableEditor.grabHorizontal = true;
				tableEditor.setEditor(chineseText[wordIndex], tableItem, 1);// 第二列显示输入中文
				wordIndex++;
			}
		}
	}


//	点击后将properties.map文件中的字典写道english2ChineseSet集合中，免得每次都需要不断地重复输入
	private final class ChinezationListener implements MouseListener {

		@Override
		public void mouseDoubleClick(MouseEvent arg0) {
		}

		@Override
		public void mouseDown(MouseEvent arg0) {
		}

		@Override
		public void mouseUp(MouseEvent arg0) {
			// 在这里添加鼠标单击后的相关操作 //生成映射
			for (int i = 0; i < english2ChineseSet.size(); i++) {
				propertiesValueWordMap.put(englishText[i].getText(), chineseText[i].getText());
			}
			Iterator<File> sourceFileVectorIterator = sourcePropertiesFileVector.iterator();
			// 调用本地函数，依次生成所有的目标文件
			while (sourceFileVectorIterator.hasNext()) {
				File sourceFile = sourceFileVectorIterator.next();
				String sourceFilePath = sourceFile.getAbsolutePath();
				String targetFilePath = sourceFilePath.replace(
						"resources.properties", //$NON-NLS-1$
						"resources_zh_CN.properties"); //$NON-NLS-1$
				File targetFile = new File(targetFilePath);
				// 调用本地方法替换掉本地化属性文件中的所有=符号之后的有映射的英语
				ChinezationUtil.createTargerPropertiesFile(sourceFile, targetFile, propertiesValueWordMap);// 将每一个源文件生成本地化文件
			}
			
//			把单词写入到文件中，可以供后面服用。
			writeEnglistChinese2PropertiesMapFile();
		}
//		把单词写入到文件中，可以供后面服用。
		private void writeEnglistChinese2PropertiesMapFile() {
			// 将Map写入到map文件中
			Set<?> word2ChineseSet = propertiesValueWordMap.entrySet();
			Iterator<?> word2ChineseSetIterator = word2ChineseSet.iterator();

//			把单词和中文的map写入到properties.map文件中,供下次使用
			String propertiesMapFile = projectRootPath + "/resources/bundles/properties.map"; //$NON-NLS-1$
			FileWriter writer;
			try {
				writer = new FileWriter(propertiesMapFile);
				BufferedWriter bw = new BufferedWriter(writer);
				while (word2ChineseSetIterator.hasNext()) {
					Entry<?, ?> word2ChineseEntry = (Entry<?, ?>) word2ChineseSetIterator.next();
					word2ChineseEntry.getKey();// 英语单词
					word2ChineseEntry.getValue();// 英语单词的中文
					if (word2ChineseEntry.getValue() != null) {// 如果中文不为空
						String line = word2ChineseEntry.getKey().toString()
								+ "=" //$NON-NLS-1$
								+ word2ChineseEntry.getValue().toString();
						bw.write(line);
						bw.newLine();
						bw.flush();
					}
				}
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static class UTF8FilterWebXmlConfigurationListener extends SelectionAdapter {
		@Override
		public void widgetSelected(SelectionEvent e) {
			
			WebXMLConfigureUTF8FilterByDOM.UpdateWebXMLUTF8(selectWebXMLPath);
		}
	}
	
	private static class PageEncodingListener extends SelectionAdapter {
		@Override
		public void widgetSelected(SelectionEvent e) {
			Set<String> suffixs=new HashSet<String>();
			suffixs.add("jsp");
			
			ReplaceStringOfExtendedFileInDirectionary
					.replaceStringOfExtendedFileInDirectionary(new File(
							selectProjectPath + "\\WebRoot"), "ISO-8859-1",
							"UTF-8", suffixs);

		}
	}
}